# -*- coding: utf-8 -*-
# @Time : 2023/12/26 16:16
# @Author : Z
# @Email : 1473858993@qq.com
# @File : mysql_util.py
# @Project : apitwo
import logging
import traceback

import pymysql


def connect_mysql(sql, db='help', dbuser='root', dbpwd='Tianqibucuo666!', dbhost='8.130.54.28',
                  dbport=3306):
    result = []
    # 连接数据库
    conn = pymysql.Connection(user=dbuser,password=dbpwd,host=dbhost,port=dbport)
    # 创建游标
    cur = conn.cursor()
    try:
        # 使用库
        cur.execute('use {}'.format(db))
        # 执行sql语句
        cur.execute(sql)
        # 遍历所有结果
        for i in cur.fetchall():
            result.append(i)
    except Exception as E:
        # 报错信息追踪到日志
        logging.error('sql语句{}异常'.format(sql)+str(E))
        logging.error(traceback.format_exc())
    finally:
        # 关闭游标
        if cur:
            cur.close()
        # 关闭连接数据库
        if conn:
            conn.close()
    return result